package com.jjb.www.utils;

import android.util.Base64;

import java.nio.charset.StandardCharsets;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author CRG
 * @date :2023/12/21 11:15
 * @description:
 */
public class AESUtils {
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
    private static final String SECRET_KEY = "cqsjjb!@#&2022GO"; // 替换为安全的密钥生成或获取方式
    private static final String CHARSET = "UTF-8";
    //加密
    public static String encrypt(String plaintext) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(CHARSET), "AES");

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(CHARSET));

        // 使用Base64对加密后的字节数组进行编码
        return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
    }

//解密
    public static String decrypt(Object ciphertext) throws Exception {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(CHARSET), "AES");

        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = Base64.decode((String) ciphertext, Base64.DEFAULT);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
//        if (returnType == String.class) {
//            // 如果期望返回类型是String，直接返回字符串
//            return returnType.cast(new String(decryptedBytes, CHARSET));
//        } else {
//            // 如果期望返回类型是其他类型，这里可以进行相应的类型转换处理
//            // 这里仅作为示例，具体的处理方式取决于你的需求
//            // 你可能需要定义更多的泛型参数或者使用其他的反序列化方法
//            throw new IllegalArgumentException("Unsupported returnType");
//        }
        return new String(decryptedBytes, CHARSET);
    }
}
